//
//  WBMTCategoryView.m
//  WBMTwaimai
//
//  Created by WangBiao on 16/9/21.
//  Copyright © 2016年 lsrain. All rights reserved.
//

#import "WBMTCategoryView.h"
#import "UIButton+CZAddition.h"
#import "UIColor+CZAddition.h"

@interface WBMTCategoryView ()

@property (nonatomic, strong) NSArray<UIButton *> *btnArr;

///黄线
@property (nonatomic, weak) UIView *yelloL;
@end

@implementation WBMTCategoryView
{
    UIButton *_selectedBtn;
}

#pragma make - 搭建界面
- (void)setupUI{
    NSArray *titleArr = @[@"点菜", @"评价", @"商家"];
    [titleArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = [UIButton cz_textButton:obj fontSize:14 normalColor:[UIColor cz_colorWithHex:0x555555] selectedColor:[UIColor cz_colorWithHex:0x000000]];
        
        //注册按钮事件
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        if (idx == 0) {
            btn.selected = YES;
            _selectedBtn = btn;
        }
        
        [self addSubview:btn];
    }];

#warning MT-1 - 利用Masonry进行巧妙的布局
    [self.subviews mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    [self.subviews mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self);
    }];
    
    //将控件记录在数组中
    self.btnArr = self.subviews;
    
    //黄线
    UIView *yellowL = [[UIView alloc]init];
    yellowL.backgroundColor = [UIColor cz_colorWithHex:0xffd900];
    [self addSubview:yellowL];
    [yellowL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.centerX.width.equalTo(self.btnArr[0]);
        make.height.mas_equalTo(4);
    }];
    
    //赋值
    self.yelloL = yellowL;
}

///按钮事件
- (void)btnClick:(UIButton *)sender{
    //获取按钮的索引
    NSUInteger idx = [self.btnArr indexOfObject:sender];
    //回调block
    self.categoryBlock(idx);
    //修改黄线位置
    self.off_X = sender.bounds.size.width * idx;

}

- (void)setOff_X:(CGFloat)off_X{
    _off_X = off_X;
    
    //更新黄线约束 - + 0.5让其多滚动一些再改变按钮状态
    [self.yelloL mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.btnArr[0]).offset(off_X);
    }];
    
    //黄线移动时添加动画
    [UIView animateWithDuration:.3 animations:^{
        //强制布局自控制
        [self layoutIfNeeded];
    }];
    
    //修改按钮状态
    //索引
    NSInteger idx = off_X / self.btnArr[0].bounds.size.width + 0.5;
    //取消之前的状态
    _selectedBtn.selected = NO;
    //设置当前的状态
    self.btnArr[idx].selected = YES;
    //记录当前的状态
    _selectedBtn = self.btnArr[idx];
    
}

@end
